import mammoth
import os

def docx_to_markdown(docx_path, output_dir="output"):
    # 定义 style_map，将 Word 样式映射为带样式的 HTML
    style_map = """
        p[style-name='Heading 1'] => h1:fresh
        p[style-name='Heading 2'] => h2:fresh
        p[style-name='Heading 3'] => h3:fresh

        # 居中对齐
        p[align='center'] => p:fresh[style='text-align: center;']
        # 右对齐
        p[align='right'] => p:fresh[style='text-align: right;']
        # 左对齐（可选）
        p[align='left'] => p:fresh[style='text-align: left;']
        # 两端对齐
        p[align='justify'] => p:fresh[style='text-align: justify;']

        # 处理带样式的 run（字体、大小、下划线等）
        r[style='Strong'] => strong => b
        r[style='Emphasis'] => em => i

        # 下划线文本
        u => span:underline[style='text-decoration: underline;']

        # 字体大小（Word 中的 sz 是二分之一个点，如 24 = 12pt）
        r[sz='24'] => span:large[style='font-size: 12pt;']
        r[sz='28'] => span:larger[style='font-size: 14pt;']
        r[sz='32'] => span:largest[style='font-size: 16pt;']

        # 自定义字体（可选）
        r[font='SimSun'] => span:f-simsun[style='font-family: "SimSun", serif;']
        r[font='Arial'] => span:f-arial[style='font-family: "Arial", sans-serif;']

        # 高亮颜色（示例）
        highlight => span:highlight[style='background-color: yellow;']

        # 默认段落样式
        p => p:fresh
    """
    with open(docx_path, "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file, style_map=style_map)
        html_content = result.value  # 得到 HTML 字符串
        messages = result.messages  # 警告或错误信息

        # 打印警告信息（可帮助调试）
        for message in messages:
            print(message)

    # 确保输出目录存在
    os.makedirs(os.path.dirname(output_dir+"/out.html"), exist_ok=True) if os.path.dirname(output_dir+"/out.html") else None

    # 写入 HTML 文件
    with open(output_dir+"/out.html", "w", encoding="utf-8") as f:
        # 添加基本的 HTML 结构和样式
        full_html = f"""<!DOCTYPE html>
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <title>文档转换结果</title>
        <style>
            body {{
                font-family: "SimSun", "宋体", serif;
                line-height: 1.8;
                margin: 40px auto;
                max-width: 900px;
                padding: 20px;
            }}
            .underline {{ text-decoration: underline; }}
            p {{ margin: 0.5em 0; }}
        </style>
    </head>
    <body>
    {html_content}
    </body>
    </html>"""
        f.write(full_html)

    print(f"转换完成！HTML 已保存至: {output_dir+"/out.html"}")

# 使用示例
if __name__ == "__main__":
    docx_file = "resources/治安调解协议书.docx"  # 替换为你的文件路径
    docx_to_markdown(docx_file)  # 获取两个文件路径